package com.ad.aidai.activitys.login;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ad.aidai.R;
import com.ad.aidai.activitys.main.MainActivity;
import com.ad.aidai.base.BaseActivity;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.utils.MultiStylesTextViewUtil;
import com.ad.aidai.common.widgets.edittext.ClearEditText;
import com.ad.aidai.common.widgets.edittext.PasswordEditText;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.fragments.forget_password.ForgetPasswordFragment;
import com.ad.aidai.fragments.register.RegisterFragment;
import com.ad.aidai.fragments.service_item.ServiceItemFragment;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 登录界面
 * <p>
 * Created by Yusxon on 16/11/27.
 */

public class LoginActivity extends BaseActivity implements LoginContract.View {
    /**
     * 电话号码
     */
    @BindView(R.id.et_phone)
    ClearEditText et_phone;
    /**
     * 密码
     */
    @BindView(R.id.et_password)
    PasswordEditText et_password;
    /**
     * 登录按钮
     */
    @BindView(R.id.bt_login)
    Button bt_login;
    /**
     * 服务条款的textview
     */
    @BindView(R.id.tv_terms)
    TextView tv_terms;
    /**
     * 忘记密码
     */
    @BindView(R.id.tv_forget)
    TextView tv_forget;
    /**
     * 注册
     */
    @BindView(R.id.tv_register)
    TextView bt_register;

    private LoginContract.Presenter mPresenter;
    /**
     * 登录对话框
     */
    private LoadingDialog loadingDialog;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        new LoginPresenter(this, this).subscribe();

        tv_terms.setHighlightColor(ContextCompat.getColor(this, android.R.color.transparent));
        new MultiStylesTextViewUtil(this)
                .initTextView(tv_terms)
                .appendText("登录爱代账号表示已同意 《")
                .appendColorText("爱代服务条款", R.color.colorTheme, new MultiStylesTextViewUtil.OnTextClickListener() {
                    @Override
                    public void textClick(View v, String text) {
                        getSupportFragmentManager()
                                .beginTransaction()
                                .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                                        .fragment_slide_left_exit)
                                .add(android.R.id.content, new ServiceItemFragment(), "service_item")
                                .addToBackStack("service_item")
                                .commit();
                    }
                })
                .appendText("》")
                .create();

        //进入界面,先加载保存过的手机号跟密码,如果没有则会显示为空
        mPresenter.loadPhone();
    }

    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void setPhoneNumber(String phoneNumber) {
        et_phone.setText(phoneNumber);
    }

    @Override
    public void setPassword(String password) {
        et_password.setText(password);
    }

    @Override
    public void toast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("登录中...")
                .setFailedText("登录失败")
                .setSuccessText("登录成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public void loginSuccess() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog != null && loadingDialog.isShowing()) {

                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //登录成功,进入主页
                        intoMainActivity();
                    }
                });
            }
        }).start();
    }

    @OnClick({R.id.bt_login, R.id.tv_forget, R.id.tv_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_login:
                //                loginSuccess();
                mPresenter.login(et_phone.getText().toString(), et_password.getText().toString());
                break;
            case R.id.tv_forget:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                                .fragment_slide_left_exit)
                        .add(android.R.id.content, new ForgetPasswordFragment(), "forgetPassword")
                        .addToBackStack("forgetPassword")
                        .commit();
                break;
            case R.id.tv_register:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                                .fragment_slide_left_exit)
                        .add(android.R.id.content, new RegisterFragment(), "register")
                        .addToBackStack("register")
                        .commit();
                break;
        }
    }

    @Override
    protected void subscribeEvents() {
        //添加注册成功的事件(注册成功直接跳转到主页面,并发送该事件,登录界面在此订阅该事件可以做出相应的处理,比如关闭登录activity)
        addSubscription(RxBus.getInstance()
                .toObservable()
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        if (o instanceof CommonEvent) {
                            CommonEvent event = (CommonEvent) o;
                            switch (event.getEvent()) {
                                case CommonEvent.REGISTER_FINISHED:
                                    boolean isSuccess = (boolean) event.getData();
                                    if (isSuccess) {
                                        intoMainActivity();
                                    }
                                    break;
                                case CommonEvent.RESET_PHONE_FINISHED:
                                    mPresenter.loadPhone();
                                    et_password.requestFocus();
                                    break;
                            }
                        }
                    }
                })
                .subscribe(RxBus.defaultSubscriber())
        );
    }

    /**
     * 进入主页
     */
    private void intoMainActivity() {
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        LoginActivity.this.finish();
        overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
    }
}
